import App from './App'
import uvUI from '@/uni_modules/uv-ui-tools'
import '@/framework/utils/requestInterceptor'
import bus from '@/framework/plugins/bus'
import { createSocket } from '@/framework/utils/webSokcet'
import config from '@/config'
import { getLoginUser, clearLoginInfo } from '@/hooks/login'
import '@/framework/plugins/common'
import { getPreviewPath, getToken } from '@/hooks/common'
import { getFileViewUrlByBussIds } from '@/api/list/search'
import * as Pinia from 'pinia';
import theme from '@/theme'
// Todo 这里优化一下，改去接口里判断
async function initPlugins(app){
	app.use(Pinia.createPinia());
	app.config.globalProperties.$bus = bus
	app.config.globalProperties.$config = config
	app.config.globalProperties.$getPreviewPath = getPreviewPath
	app.config.globalProperties.$getFileViewUrlByBussIds = getFileViewUrlByBussIds
	
	app.config.globalProperties.$getToken = getToken
	app.config.globalProperties.$thatThemeClassName = theme.getThatThemeClass()
	
	let isLoadSocket = false
	let socket = null
	let socketBaseUrl = config.webSocketServerUrl
	let loginUser = await getLoginUser()
	
	if(loginUser){
		let token = uni.getStorageSync("token");
		socketBaseUrl = socketBaseUrl + '?token=' + token
		socket = createSocket(socketBaseUrl,token)
		app.config.globalProperties.$socket = socket.socketTask
		isLoadSocket = true
		uni.setStorageSync("user", loginUser)
		app.config.globalProperties.$loginUserInfo = loginUser
	} else {
		// 清空登录信息
		clearLoginInfo()
		app.config.globalProperties.$loginUserInfo = null
	}
	bus.$on('loginSuccess',async (res) => {
		if(!isLoadSocket){
			let token = uni.getStorageSync("token");
			socket = createSocket(socketBaseUrl,token)
			app.config.globalProperties.$socket = socket.socketTask
			loginUser = await getLoginUser()
			uni.setStorageSync("user", loginUser)
			app.config.globalProperties.$loginUserInfo = loginUser
		}
	})
	app.mixin({
		onLoad(){
			theme.initTheme()
		}
	})
	// app.mixin(sharePages)
}	

// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'

try {
  function isPromise(obj) {
    return (
      !!obj &&
      (typeof obj === "object" || typeof obj === "function") &&
      typeof obj.then === "function"
    );
  }

  // 统一 vue2 API Promise 化返回格式与 vue3 保持一致
  uni.addInterceptor({
    returnValue(res) {
      if (!isPromise(res)) {
        return res;
      }
      return new Promise((resolve, reject) => {
        res.then((res) => {
          if (res[0]) {
            reject(res[0]);
          } else {
            resolve(res[1]);
          }
        })
      })
    },
  })
} catch (error) { }

const app = new Vue({
  ...App
})
initPlugins(app)
app.$mount()


// #endif
// #ifdef VUE3

// #ifndef VUE3
Vue.use(uvUI);
// #endif
// #ifdef VUE3

// #endif

import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  
  initPlugins(app)
  
  return {
    app
  }
}
// #endif
